﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using System.Web.Mvc.Ajax;
using CMN.Models;
using CMN.Models.Interfaces;
using CMN.Entity;
using CMN.Controllers;
using CMN.Controllers.Filters;
using CMN.Common;
using System.Text;
using CMN.UI;
using CMN.Framework;
using CMN.Config;
namespace CMN.Controllers
{
   
    [LoggerFilter()]
    [ExceptionFilter()]
    [ExecutionTimingAttribute()]
    public class SearchController : Controller
    {
        [CompressFilter]
        [CacheFilterAttribute]
        public string Index(string channel, string searchWords, string pageIndex)
        {
            if (searchWords == null)
            {
                searchWords = "";
            }
            DateTime dt = DateTime.Now;
            PageHelperEntity pageHelper = new PageHelperEntity();
            Normal_ChannelEntity channelEntity = null;
            pageHelper.ParentDir = "";
            if (!string.IsNullOrEmpty(channel))  //是否所属频道只有一个
            {
                channelEntity = MvcWebCacheManager.GetNormal_ChannelByDir(channel);
                if (channelEntity != null)
                {
                    pageHelper.Channel = channelEntity;
                    pageHelper.ChannelId = channelEntity.Id;
                    pageHelper.ParentDir = channelEntity.Dir;
                    pageHelper.ParentChannel = channelEntity;
                }
                else
                    pageHelper.ParentDir = "";
                
            }
            if (pageHelper.Channel == null)
            {
                pageHelper.Channel = new Normal_ChannelEntity();

            }
            pageHelper.PageIndex = Utils.StringToInt(pageIndex, 1);
            searchWords = searchWords.Replace("?", "");
            pageHelper.Title = searchWords;
            pageHelper.Description = string.Empty;
            pageHelper.Keywords = string.Empty;
            searchWords = ValidateChinese(searchWords);
            searchWords = Utils.GetSubString(searchWords, 40, "");
            Common.Filter.FastFilter ff = CMN.Framework.MvcWebCacheManager.GetBadWordFastFilter();
            Common.RegExpression.RegContext regcontent = new Common.RegExpression.RegContext();
            Common.RegExpression.URLRegExpression urlReg = new Common.RegExpression.URLRegExpression();
            regcontent.Context = searchWords;
            regcontent.Operator = 'R';
            regcontent.Replacement = "";
            urlReg.Evaluate(regcontent);
            searchWords = regcontent.Context;
            if (ff.HasBadWord(searchWords))
            {
                AppLog.Write(string.Concat("HasBadWord",Utils.GetIP(),searchWords),AppLog.LogMessageType.Debug);
                searchWords = "";
            }
           // searchWords = ff.Replace(searchWords);
            
            LuceneHelper lucence = new LuceneHelper();
           List<string> searchList= lucence.GetKeyWordsList(searchWords);
           pageHelper.SearchWords = searchWords;
           pageHelper.Type = PageType.SearchPage;
           if (pageHelper.PageIndex == 1 && searchList.Count>2)
            {
               
            }

           SiteConfigInfo siteInfo = SiteConfigs.GetSiteConfig();
            if (channelEntity == null || siteInfo.IsZhanQun )
            {
                pageHelper.Url = string.Concat("/search/",Utils.UrlEncode( searchWords));
            }
            else
            {
                pageHelper.Url = string.Concat("/search/", channelEntity.Dir, "/",Utils.UrlEncode(searchWords));
            }
           
            BaseTemplateDisplay searchTemplate = new BaseTemplateDisplay(pageHelper);
            string strReturn = searchTemplate.Display();
            searchTemplate.Dispose();

            return strReturn;

        }
        public string Insert( string searchWord,string channel)
        {
            string strReturn = string.Empty;
            if (string.IsNullOrEmpty(searchWord))
            {
               return  strReturn = "{\"result\":\"1\",\"returnval\":\"\"}";
            }
            searchWord = Utils.ReplaceString(searchWord, "[A-Za-z0-9_.]", "", false);
            try
            {
                if (searchWord.Length > 4)
                {
                    Normal_SearchContentService searchService = new Normal_SearchContentService();
                    Normal_SearchContentEntity searchEntity = new Normal_SearchContentEntity();
                    QueryParam qp = new QueryParam();
                    qp.PageSize = 1;
                    qp.PageIndex = 1;
                    qp.Where = string.Concat(" SearchContent='", searchWord, "'");
                    int recordCount = 0;
                    List<Normal_SearchContentEntity> searchList = searchService.List(qp, out recordCount);
                    searchEntity.SearchContent = searchWord;
                    if (channel != null)
                        searchEntity.SearchType = channel.ToLower();
                    if (recordCount < 1)
                    {
                        searchEntity.SearchNum = 1;
                        searchEntity.DataTable_Action = DataTableAction.Insert;
                        searchService.Insert(searchEntity);
                    }
                    else
                    {
                        searchEntity = searchList[0];
                        searchEntity.SearchNum = searchEntity.SearchNum + 1;
                        searchEntity.DataTable_Action = DataTableAction.Update;
                        searchService.Insert(searchEntity);
                    }
                }
                strReturn = "{\"result\":\"1\",\"returnval\":\"\"}";
            }
            catch (Exception ex)
            {
                AppLog.Write(ex.Message, AppLog.LogMessageType.Error, ex);
                strReturn = "{\"result\":\"0\",\"returnval\":\""+ex.Message+"\"}";
            }
            return strReturn;
        }
        //过滤乱码--不能全部过滤，汉字乱码过滤不了。
        protected  string ValidateChinese(string s)
        {
            int max = s.Length;
            StringBuilder sb = new StringBuilder();
            for (int i = 0; i < max; i++)
            {
                if (System.Text.RegularExpressions.Regex.IsMatch(@s[i].ToString(), @"[\p{P}a-zA-Z0-9\u4e00-\u9fbb]+$"))
                {

                    sb.Append(s[i].ToString());
                   
                }
            }
            return sb.ToString();
        }
        
    }
}
